<template>
  <div v-if="articleId">
    <Comment
      v-for="comment in commentList"
      :comment="comment"
      :key="comment.id"
      style="padding-top:1em;"
    ></Comment>
      <el-pagination
    layout="prev, pager, next"
    :page-size="6"
    :small="true"
    @current-change="handlePageChanged"
    :hide-on-single-page="true"
    :total="total">
  </el-pagination>
  </div>
</template>

<script>
export default {
  props: {
    articleId: { type: Number },
    rootId: { type: Number },
  },
  data() {
    return {
      freshKey:'',
      total: 0,
      commentList: [],
      url: "",
    };
  },
  beforeCreate: function () {
    this.$options.components.Comment = require("./Comment").default;
  },
  mounted() {
    if (this.articleId) {
      this.url = "comments/?ordering=-created_at&&article=" + this.articleId+'&&parent=-1';
    }
    if (this.rootId) {
      this.url = "comments/" + this.rootId + "/full_chat/?ordering=-created_at";
    }
    this.getComments();
  },
  methods: {
    getComments() {
      this.$http.get(this.url).then((res) => {
        this.commentList = res.data.results;
        this.total = res.data.count
      });
    },
    handlePageChanged(currentPage) {
      const pos = this.url.search('[Pp][Aa][Gg][Ee]');
      const questionPos = this.url.indexOf('?');
      const joinChar = questionPos == -1 ? '?' : '&';
      if (pos == -1) {
        this.url += `${joinChar}page=${currentPage}`;
      } else {
        const regex = /(page=)\d+/;
        this.url = this.url.replace(
          regex,
          `$1${currentPage}`,
        );
      }
      this.getComments()
    }
  },
};
</script>

<style>
</style>